using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Dao;
using Entities;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
namespace Doctors_WebForum.Admin.UIControls
{
    public partial class Feedbacks : System.Web.UI.UserControl
    {
        private IList<Feedback> listFeedBacks;
        private FeedbackData feedBackData;
        private Feedback feedback;
        private int PageSize = 10;
        public Feedbacks()
        {
            listFeedBacks = new List<Feedback>();
            feedBackData = new FeedbackData();
            feedback = new Feedback();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData(1, PageSize, 1, false, false);
            }
        }
        #region Implement function sort
        //Sort by FullName
        protected void SortName(object sender, EventArgs e)
        {
            listFeedBacks = feedBackData.SortByColumn("FullName");
            dtlUser.DataSource = listFeedBacks;
            dtlUser.DataBind();
            HiddenThenSort();
        }
        //Sort by Email
        protected void SortEmail(object sender, EventArgs e)
        {
            listFeedBacks = feedBackData.SortByColumn("Email");
            dtlUser.DataSource = listFeedBacks;
            dtlUser.DataBind();
            HiddenThenSort();
        }
        //Sort by SendDate
        protected void SendDate(object sender, EventArgs e)
        {
            listFeedBacks = feedBackData.SortByColumn("SendDate");
            dtlUser.DataSource = listFeedBacks;
            dtlUser.DataBind();
            HiddenThenSort();
        }
        //Hidden control then implemnt function sort
        private void HiddenThenSort()
        {
            lblResultPaging.Visible = false;
            lbtnPrevious.Visible = false;
            lbtnNext.Visible = false;
            DLPAGING.Visible = false;
        }
        #endregion
        #region Implement pagging for datalist control
        //Return list user with pagging 
        protected void lbkListUser_Click(object sender, EventArgs e)
        {
            lblResultPaging.Visible = true;
            lbtnPrevious.Visible = true;
            DLPAGING.Visible = true;
            lbtnNext.Visible = true;
            dtlUser.Visible = true;
            lblMessage.Visible = false;
            LoadData(1, PageSize, 1, false, false);
        }
        //Count total of page
        private int TotalPage
        {
            get
            {
                if (ViewState["TotalPage"] == null)
                    return 0;
                else
                    return Convert.ToInt32(ViewState["TotalPage"]);
            }
            set
            {
                ViewState["TotalPage"] = value;
            }
        }
        //Count current record
        private int CurrentRecord
        {
            get
            {
                if (ViewState["CurrentRecord"] == null)
                    return 0;
                else
                    return (int)ViewState["CurrentRecord"];
            }
            set
            {
                ViewState["CurrentRecord"] = value;
            }
        }
        //Count total of page
        private int CurrentTotalPage
        {
            get
            {
                if (ViewState["CurrentTotalPage"] == null)
                    return PageSize;
                else
                    return Convert.ToInt32(ViewState["CurrentTotalPage"]);
            }
            set
            {
                ViewState["CurrentTotalPage"] = value;
            }
        }
        //Display next record of data
        protected void NextPage(object sender, EventArgs e)
        {
            string[] Page = new string[2];
            int SelectedPage = 1;
            //txtPageNo.Text = "";
            foreach (DataListItem DlItem in DLPAGING.Items)
            {
                if (DlItem.FindControl("lblNumber").Visible)
                {
                    SelectedPage = Int32.Parse(((Label)DlItem.FindControl("lblNumber")).Text.Trim()) + 1;
                    LinkButton lnkbtn = (LinkButton)DlItem.FindControl("imgbtnNumber");
                    Page = lnkbtn.CommandArgument.Split(new char[] { '-' });
                    break;
                }
            }

            int StartNo = Int32.Parse(Page[1]) + 1;
            int Last = StartNo + PageSize - 1;
            LoadData(StartNo, Last, SelectedPage, true, false);
        }
        //Display preview record of data
        protected void lbtnPrevious_Click(object sender, EventArgs e)
        {
            string[] PAGE = new string[2];
            int SelectedPage = 1;
            foreach (DataListItem DlItem in DLPAGING.Items)
            {
                if (DlItem.FindControl("lblNumber").Visible)
                {
                    SelectedPage = Int32.Parse(((Label)DlItem.FindControl("lblNumber")).Text.Trim()) - 1;
                    LinkButton lnkbtn = (LinkButton)DlItem.FindControl("imgbtnNumber");
                    PAGE = lnkbtn.CommandArgument.Split(new char[] { '-' });
                    break;
                }
            }

            int StartNo = Int32.Parse(PAGE[0]) - PageSize;
            int Last = (StartNo - 1) + PageSize;
            LoadData(StartNo, Last, SelectedPage, false, true);
        }
        //Pagging data with datalist control
        protected void DLPAGING_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "Paging")
            {
                char[] split = new char[] { '-' };
                string[] PAGE = e.CommandArgument.ToString().Split(split);

                if (PAGE.Length > 0)
                {
                    LinkButton lnl = (LinkButton)DLPAGING.Items[e.Item.ItemIndex].FindControl("imgbtnNumber");
                    Label lbl = (Label)DLPAGING.Items[e.Item.ItemIndex].FindControl("lblNumber");
                    lbl.Visible = true;
                    lnl.Visible = false;
                    LoadData(Int32.Parse(PAGE[0]), Int32.Parse(PAGE[1]), Int32.Parse(lbl.Text.Trim()), false, false);
                }
            }
        }
        //Load data on datalist control
        private void LoadData(int paging_StartIndex, int paging_EndIndex, int selectedPage, bool isNext, bool isPrevious)
        {
            SqlConnection conn = new SqlConnection(Common.SQLDBHelper.CONN_STRING);
            SqlCommand Cmd = new SqlCommand("[SP_PaggingFeedBacks]", conn);
            Cmd.Parameters.AddWithValue("@StartIndex", paging_StartIndex);
            Cmd.Parameters.AddWithValue("@EndIndex", paging_EndIndex);
            Cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter SqlAda = new SqlDataAdapter(Cmd);
            DataSet DsStudentDetails = new DataSet();
            SqlAda.Fill(DsStudentDetails);
            conn.Close();

            if (DsStudentDetails.Tables.Count > 0 && DsStudentDetails.Tables[0].Rows.Count > 0)
            {
                TotalPage = (Int32.Parse(DsStudentDetails.Tables[0].Rows[0]["row"].ToString()) / PageSize) + ((Int32.Parse(DsStudentDetails.Tables[0].Rows[0]["row"].ToString()) % PageSize) > 0 ? 1 : 0);

                //Paging Table
                CurrentRecord = DsStudentDetails.Tables[0].Rows.Count;

                DataTable tDataTable = new DataTable("PagingTable");
                tDataTable.Columns.Add(new DataColumn("LinkButtonVisible", typeof(bool)));
                tDataTable.Columns.Add(new DataColumn("DisplayName", typeof(string)));
                tDataTable.Columns.Add(new DataColumn("Value", typeof(string)));
                tDataTable.Columns.Add(new DataColumn("LabelVisible", typeof(bool)));

                int StartPage = 1;
                if (TotalPage > 10)
                {
                    if (selectedPage > CurrentTotalPage && isNext)
                        CurrentTotalPage = selectedPage;
                    else if ((selectedPage <= CurrentTotalPage - 10) && isPrevious)
                    {
                        if (isNext)
                            CurrentTotalPage = (selectedPage > 10) ? selectedPage : 10;
                        else
                            CurrentTotalPage = CurrentTotalPage - 1;
                    }
                    StartPage = (CurrentTotalPage + 1) - 10;

                    if (StartPage <= 0)
                        StartPage = 1;
                }
                else
                    CurrentTotalPage = TotalPage;

                for (int loop = StartPage; loop <= CurrentTotalPage; loop++)
                {
                    DataRow DRow = tDataTable.NewRow();
                    if (loop == selectedPage)
                    {
                        DRow["LinkButtonVisible"] = false;
                        DRow["LabelVisible"] = true;
                    }
                    else
                    {
                        DRow["LinkButtonVisible"] = true;
                        DRow["LabelVisible"] = false;
                    }

                    int TrimValue = (((loop - 1) * PageSize) + 1);
                    DRow["Value"] = TrimValue + "-" + Decimal.Multiply(loop, PageSize);
                    DRow["DisplayName"] = loop;
                    tDataTable.Rows.Add(DRow);
                }

                lbtnNext.Visible = (selectedPage != TotalPage);
                lbtnPrevious.Visible = (selectedPage > 1);

                DLPAGING.DataSource = tDataTable.DefaultView;
                DLPAGING.DataBind();

                if (TotalPage > 1)
                {
                    int CurrentPageSize = (DsStudentDetails.Tables[0].Rows.Count == PageSize) ? paging_EndIndex : paging_StartIndex + DsStudentDetails.Tables[0].Rows.Count - 1;

                    lblResultPaging.Text = "Results " + paging_StartIndex + " - " + CurrentPageSize + " of " + (Int32.Parse(DsStudentDetails.Tables[0].Rows[0]["row"].ToString()));

                    lblResultPaging.Visible = true;
                }
                else
                {
                    lblResultPaging.Visible = false;
                }

                dtlUser.DataSource = DsStudentDetails.Tables[0];
                dtlUser.DataBind();
            }
        }
        #endregion

        protected void dtlUser_DeleteCommand(object source, DataListCommandEventArgs e)
        {
            // get the primary key column value, and editing data
            string id = dtlUser.DataKeys[e.Item.ItemIndex].ToString();
            // write code to delete data here
            if (feedBackData.DeleteById(Utility.ToInt(id)) == true)
            {
                lblMessage.Visible = true;
                lblMessage.Text = "<font style='color:red;'> delete success !</font>";
                dtlUser.EditItemIndex = -1;
                LoadData(1, PageSize, 1, false, false);
            }
            else
            {
                lblMessage.Text = "<font style='color:red;'>delete not success !</font>";
            }
        }

        protected void txtSearch_TextChanged(object sender, EventArgs e)
        {
            string searchUser = txtSearch.Text.Trim();

            if (searchUser != string.Empty)
            {
                listFeedBacks = feedBackData.SearchByTitle(searchUser);
                if (listFeedBacks.Count != 0)
                {
                    int countUser = listFeedBacks.Count;
                    dtlUser.Visible = true;
                    dtlUser.DataSource = listFeedBacks;
                    dtlUser.DataBind();
                    lblMessage.Visible = true;
                    lblMessage.Text = "<b> Have total <font style = 'color:#C87431;'>" + countUser + "</font> tilte for result " + "<font style = 'color:#C87431;'>" + searchUser + "</font><b/>";
                    txtSearch.Focus();
                    HiddenThenSort();
                }
                else
                {
                    dtlUser.Visible = false;
                    HiddenThenSort();
                    lblMessage.Text = "<b>No result for <font style='color: #C87431;'>" + searchUser + "</font></b>"; txtSearch.Focus();
                }
            }
            else
            {
                dtlUser.Visible = false;
                lblMessage.Visible = true;
                lblMessage.Text = "<b>Please enter name to search !</b>";
                txtSearch.Focus();
                HiddenThenSort();
            }
        }

    }
}